package qe.spider.trade;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.ini4j.Ini;
import qe.spider.MainSelect;
import qe.spider.trade.huaxin.StockTradeHuaXin;
import qe.spider.trade.ths_lanzi.StockTradeTHSLanZi;
import qe.spider.vo.GoodStock;
import qe.spider.vo.Stock;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

import static qe.spider.trade.SendBuySignal.BaseTradePath;

@Slf4j
public class SendSellSignal {

    private static Ini ini;

    public static Ini getIni() throws IOException {
        if (ini == null)
            ini = new Ini(FileUtil.touch(BaseTradePath + System.getProperty("wsn_port", "8888") + "\\sell.ini"));
        return ini;
    }

    public static Boolean sell(String sellType, GoodStock gs, Stock stock) throws IOException {
        Ini ini = getIni();
        String day = gs.getUpTime().substring(0, 10).replaceAll("-", "");
        try {   //记录到ini卖出信号
            Map<String, String> map = ini.get(day);
            if (null == map || !map.containsKey(gs.getCode())) {
                ini.put(day, gs.getCode(), "0");
                ini.store();
            }
        } catch (IOException e) {
            log.error("记录卖出信号{}（{}）到ini出错", gs.getCode(), gs.getName(), e);
            e.printStackTrace();
        }
        StockTradeHuaXin.accounts.values().stream().filter(t -> sellType.contains(Optional.ofNullable(t.getCfg().getSellStrategy()).orElse("fall_avg"))).forEach(trade -> {
            try {
                trade.sell(stock);
            } catch (Exception e) {
                log.error("华鑫卖出{}（{}）出错----账号：{}({})", gs.getCode(), gs.getName(), trade.getCfg().getUserName(), trade.getCfg().getUserId(), e);
            }
        });
        StockTradeTHSLanZi.accounts.values().stream().filter(t -> sellType.contains(Optional.ofNullable(t.getCfg().getSellStrategy()).orElse("fall_avg"))).forEach(trade -> {
            try {
                trade.sell(stock);
            } catch (Exception e) {
                log.error("同花顺卖出{}（{}）出错----账号：{}({})", gs.getCode(), gs.getName(), trade.getUserName(), trade.getUserId(), e);
            }
        });
        return ini.get(day).containsKey(gs.getCode());
    }
}
